package com.gome.axwl.aoc.web.controller.app;

import com.gome.axwl.aoc.common.constants.AppVersionConstants;
import com.gome.axwl.aoc.common.util.ExcelOprateUtil;
import com.gome.axwl.aoc.common.util.XskyS3Util;
import com.gome.axwl.aoc.entity.dto.AppVersionDto;
import com.gome.axwl.aoc.entity.dto.PageParamDto;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.facade.AppVersionFacade;
import com.gome.common.utils.StringUtil;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 项目名称：gome-axwl-aoc-web
 * 类名称：AppVersionController
 * 类描述：
 * 创建人：chengh
 * 创建时间：2018年4月27日16:07:16
 */
@Api(tags = "APP版本管理")
@RestController
@RequestMapping(value = "/appVersion")
public class AppVersionController {

    private final static Logger log = LoggerFactory.getLogger(AppVersionController.class);

    @Autowired
    AppVersionFacade appVersionFacade;

    @ApiOperation(value = "查询app版本管理列表", notes = "development by chengh")
    @ResponseBody
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public ResultData<PageResultDto<AppVersionDto>> getList(@RequestBody PageParamDto pageParamDto, HttpServletRequest request) {
        log.info("调用AppVersionController.getList(查询app版本管理列表),参数为:" + pageParamDto.toString());
        return appVersionFacade.getList(pageParamDto);
    }

    @ApiOperation(value = "删除版本管理信息", notes = "development by chengh")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "int", required = true)
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResultData deleteAppVersionById(@RequestBody AppVersionDto appVersionDto, HttpServletRequest request) {
        log.info("调用AppVersionController.deleteAppVersionById(删除版本管理信息),参数为:" + appVersionDto.toString());
        return appVersionFacade.delete(appVersionDto.getId());
    }

    @ApiOperation(value = "发布版本", notes = "development by chengh")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "int", required = true)
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public ResultData publish(@RequestBody AppVersionDto appVersionDto, HttpServletRequest request) {
        log.info("调用AppVersionController.publish(发布版本),参数为:" + appVersionDto.toString());
        return appVersionFacade.publish(appVersionDto);
    }

    @ApiOperation(value = "新增APP版本", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "versionCode", value = "版本编号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionName", value = "版本名称", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionUpdateContent", value = "更新内容", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionType", value = "版本类型{0-非强制更新  1-强制更新}", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionPushScope", value = "推送范围{0-全员推送  1-部分dc}", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "verisonDcPath", value = "dc文件的存储路径", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionSystemType", value = "系统类型{0-android  1-ios}", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionAppPath", value = "app的存储路径", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "versionStatus", value = "状态{0-未发布  1-已发布  2-已删除}", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultData add(@RequestBody AppVersionDto appVersionDto, HttpServletRequest request) {
        log.info("调用AppVersionController.add(新增APP版本),参数为:" + appVersionDto.toString());
        return appVersionFacade.add(appVersionDto);
    }

    /**
     * 上传apk文件
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadApk", method = RequestMethod.POST)
    public ResultData uploadApk(@RequestParam(value="file")MultipartFile file, @RequestParam(value="saveFileName")String saveFileName, HttpServletRequest request) {
        //上传apk到文件服务器
        String fileName = saveFileName + ".apk";
        String downLoadUrl = XskyS3Util.uploadAndReturnUrl(file, null, fileName);
        if (StringUtil.isEmpty(downLoadUrl)) {
            log.error("上传APK失败.");
            return new ResultData(ErrorCode.FAILOR, ErrorCode.FAILOR_MSG);
        }
        downLoadUrl = downLoadUrl.replaceAll("bjgc3.gos.gomedc.com","bjgc3-gos.gomecloud.com");
        return new ResultData<>(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG, downLoadUrl);
    }

    /**
     * 上传DCCode文件
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadDcExcel", method = RequestMethod.POST)
    public ResultData uploadDcExcel(@RequestParam(value="file") MultipartFile file, @RequestParam(value="saveFileName",required = false) String saveFileName, HttpServletRequest request) {
        try {
            List<String> dcCodeList = ExcelOprateUtil.getDcCodeList(file);      //获取dcCode集合
            if (dcCodeList == null) {
                return new ResultData(ErrorCode.FAILOR, "上传文件失败.");
            }
            ResultData<List<Integer>> resultData = appVersionFacade.checkDcCodeList(dcCodeList);
            if (resultData.getCode() != ErrorCode.SUCCESS) {
                return new ResultData(ErrorCode.FAILOR, "上传文件失败.");
            }
            if (resultData.getData().size() > 0) {          //如果dc编码有错误
                for (Integer integer : resultData.getData()) {
                    dcCodeList.set(integer, dcCodeList.get(integer) + "-");
                }
            }
            String dcCodeStrings = String.join(",", dcCodeList);        //dc编码用逗号隔开的字符串
            ByteArrayInputStream input = new ByteArrayInputStream(dcCodeStrings.getBytes());
            XskyS3Util.createTxt(saveFileName + ".txt", input);
            if(resultData.getData().size() > 0){        //如果dc编码有错误
                return new ResultData<>(AppVersionConstants.dcCodeErrorCode, AppVersionConstants.doCodeErrorMsg, dcCodeStrings);
            }
            return new ResultData<>(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG, dcCodeStrings);
        } catch (Exception e) {
            log.error("上传excel失败.");
            return new ResultData(ErrorCode.FAILOR, "上传文件失败.");
        }
    }

    /**
     * 下载错误的excel
     *
     * @param saveFileName
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/downLoadExcel")
    public void downLoadExcel(String saveFileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            String content = XskyS3Util.readFile(saveFileName + ".txt");
            String[] dcCodes = content.split(",");
            List<String> dcCodeList = Arrays.asList(dcCodes);
            XSSFWorkbook workbook = ExcelOprateUtil.createExcel(dcCodeList);
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=" + new String(("DC编码.xlsx").getBytes(), "iso-8859-1"));
            response.setContentType("application/msexcel");
            workbook.write(output);
            output.close();
        } catch (Exception e) {
            log.error("下载错误的EXCEL失败.");
        }
    }


}
